package com.demo.springBootDemo07.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.demo.springBootDemo07.entity.Dept;
import com.demo.springBootDemo07.service.DeptService;

@Service
@Primary
public class DeptServiceImpl2 implements DeptService {

	@Resource(name = "deptRedisTemplate")
	private RedisTemplate<String, Dept> template;

	@Resource(name = "deptRedisTemplate") //
	private ValueOperations<String, Dept> ops;

	private static final String DOMAIN = "DEPT";
	private static final String KEY_PATTERN = "%s:%s"; // key为"表名:PKID"的格式

	@Override
	public List<Dept> findList() {
		List<Dept> list = new ArrayList<>();
		String key = String.format(KEY_PATTERN, DOMAIN, "*");
		Set<String> keys = this.template.keys(key);
		if (!CollectionUtils.isEmpty(keys)) {
			list = this.ops.multiGet(keys);
		}
		return list;
	}

	@Override
	public Dept getByPrimaryKey(Integer deptno) {
		Dept dept = null;
		String key = String.format(KEY_PATTERN, DOMAIN, deptno);
		if (this.template.hasKey(key)) {
			dept = this.ops.get(key); // get
		}
		return dept;
	}

	@Override
	public Dept addDept(final Dept dept) {
		String key = String.format(KEY_PATTERN, DOMAIN, dept.getDeptno());
		this.ops.set(key, dept); // add
		return dept;
	}

	@Override
	public Dept updateDept(final Integer deptno, final Dept dept) {
		Dept deptOrg = null;
		String key = String.format(KEY_PATTERN, DOMAIN, deptno);
		if (this.template.hasKey(key)) {
			deptOrg = this.ops.get(key);

			this.ops.set(key, dept); // update
		}
		return deptOrg;
	}

	@Override
	public Dept deleteByPrimaryKey(final Integer deptno) {
		Dept deptOrg = null;
		String key = String.format(KEY_PATTERN, DOMAIN, deptno);
		if (this.template.hasKey(key)) {
			deptOrg = this.ops.get(key);

			this.template.delete(key); // delete
		}
		return deptOrg;
	}

}
